/**
 * 国内指数卡片列表组件（WebSocket实时数据）
 */

import React from 'react';
import { useRealtimeMarketIndexes } from '../hooks/useRealtimeMarketIndexes';
import IndexCard from './IndexCard';
import { IndexData } from '@shared/types/market';

interface IndexCardListProps {
  codes?: string[];
  onIndexClick?: (code: string) => void;
}

// 示意数据
const mockIndexes: IndexData[] = [
  {
    code: '000001.SH',
    name: '上证指数',
    current: 3245.67,
    change: 12.34,
    change_pct: 0.38,
    high: 3258.90,
    low: 3235.12,
    open: 3240.00,
    prev_close: 3233.33,
    volume: 250000000,
    amount: 320000000000,
    timestamp: new Date().toISOString(),
  },
  {
    code: '399001.SZ',
    name: '深证成指',
    current: 10567.89,
    change: -23.45,
    change_pct: -0.22,
    high: 10598.76,
    low: 10554.32,
    open: 10591.34,
    prev_close: 10591.34,
    volume: 180000000,
    amount: 210000000000,
    timestamp: new Date().toISOString(),
  },
  {
    code: '399006.SZ',
    name: '创业板指',
    current: 2145.32,
    change: 8.76,
    change_pct: 0.41,
    high: 2152.10,
    low: 2138.45,
    open: 2140.00,
    prev_close: 2136.56,
    volume: 120000000,
    amount: 150000000000,
    timestamp: new Date().toISOString(),
  },
  {
    code: 'HSI',
    name: '恒生指数',
    current: 18234.56,
    change: 45.67,
    change_pct: 0.25,
    high: 18298.43,
    low: 18187.92,
    open: 18200.00,
    prev_close: 18188.89,
    volume: 95000000,
    amount: 120000000000,
    timestamp: new Date().toISOString(),
  },
];

const IndexCardList: React.FC<IndexCardListProps> = ({ codes, onIndexClick }) => {
  const { 
    data: indexes, 
    isLoading, 
    error,
    isConnected,
    source,
    strategy 
  } = useRealtimeMarketIndexes(codes);

  const isError = !!error;
  
  // 调试日志
  console.log('[IndexCardList] 渲染状态:', {
    codes,
    indexes,
    indexesLength: indexes?.length,
    isLoading,
    isConnected,
    source,
    strategy,
    error
  });
  
  // 使用真实数据或示意数据（即使在加载中也显示数据，通过 WebSocket 实时更新）
  const displayIndexes = (indexes && indexes.length > 0 ? indexes : mockIndexes).filter((index): index is IndexData => index !== null);

  // 不再显示整页加载状态，而是让数据通过 WebSocket 实时推送更新
  // 只在首次加载且没有任何数据时显示骨架屏
  const showSkeleton = isLoading && (!indexes || indexes.length === 0);
  
  console.log('[IndexCardList] 显示状态:', {
    showSkeleton,
    displayIndexesLength: displayIndexes.length,
    displayIndexes: displayIndexes.map(d => ({ code: d.code, name: d.name }))
  });

  if (showSkeleton) {
    return (
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
          gap: '16px',
        }}
      >
        {[1, 2, 3, 4].map((i) => (
          <div
            key={i}
            style={{
              backgroundColor: '#f5f5f5',
              padding: '20px',
              borderRadius: '8px',
              height: '160px',
              animation: 'pulse 1.5s ease-in-out infinite',
            }}
          />
        ))}
      </div>
    );
  }

  return (
    <div>
      {/* WebSocket 连接状态指示器 */}
      <div
        style={{
          marginBottom: '12px',
          display: 'flex',
          alignItems: 'center',
          gap: '8px',
          fontSize: '12px',
          color: '#666',
        }}
      >
        <div
          style={{
            width: '8px',
            height: '8px',
            borderRadius: '50%',
            backgroundColor: isConnected ? '#52c41a' : '#faad14',
            animation: isConnected ? 'pulse 2s ease-in-out infinite' : 'none',
          }}
        />
        <span>
          {isConnected 
            ? `🚀 实时推送 (${source})` 
            : `⏱️ 轮询模式 (${source})`
          }
        </span>
        {strategy && (
          <span style={{ color: '#999', fontSize: '11px' }}>
            · {strategy === 'websocket' ? 'WebSocket' : strategy === 'polling' ? 'HTTP轮询' : '混合模式'}
          </span>
        )}
      </div>

      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
          gap: '16px',
        }}
      >
        {isError && (
          <div
            style={{
              gridColumn: '1 / -1',
              backgroundColor: '#fffbe6',
              border: '1px solid #ffe58f',
              borderRadius: '8px',
              padding: '12px 16px',
              color: '#faad14',
              fontSize: '14px',
              display: 'flex',
              alignItems: 'center',
              gap: '8px',
            }}
          >
            <span>💡</span>
            <span>数据加载失败，显示示意数据</span>
          </div>
        )}
        {displayIndexes.map((index) => (
          <IndexCard
            key={index.code}
            data={index}
            onClick={onIndexClick ? () => onIndexClick(index.code) : undefined}
          />
        ))}
      </div>
    </div>
  );
};

export default IndexCardList;

